/**********************************************************
 * Copyright © 2024 Walkline Wang (https://walkline.wang)
 * Gitee: https://gitee.com/walkline/keypad-for-ops
 **********************************************************/
#include "effect.h"

void EFFECT::gradient(uint8_t *color) {
    static uint8_t current_index = 0;
    static uint8_t next_index = 1;
    static uint8_t step = 1;

    color[0] =
        COLORS[current_index][0] +
        (COLORS[next_index][0] - COLORS[current_index][0]) * step / steps;
    color[1] =
        COLORS[current_index][1] +
        (COLORS[next_index][1] - COLORS[current_index][1]) * step / steps;
    color[2] =
        COLORS[current_index][2] +
        (COLORS[next_index][2] - COLORS[current_index][2]) * step / steps;

    step++;

    if (step > steps) {
        step = 1;
        current_index =
            (current_index + 1) % (sizeof(COLORS) / sizeof(COLORS[0]));
        next_index = (next_index + 1) % (sizeof(COLORS) / sizeof(COLORS[0]));
    }
}

// https://github.com/adafruit/Adafruit_NeoPixel
void EFFECT::rainbow(uint8_t &index, uint8_t *color) {
    static long hue = 0;
    static uint8_t count = 0;
    int16_t step = 256 * 1;
    uint8_t loops = 1;

    color_hsv(hue + (count * 65536L / LEDS_COUNT), color);

    index = count;
    count++;

    if (count >= LEDS_COUNT) {
        count = 0;
        hue += step;

        if (hue >= loops * 65535) {
            hue = 0;
        }
    }
}

// https://github.com/adafruit/Adafruit_NeoPixel
void EFFECT::color_hsv(uint16_t hue, uint8_t *color) {
    uint8_t r, g, b;

    hue = (hue * 1530L + 32768) / 65536;

    if (hue < 510) {
        b = 0;
        if (hue < 255) {
            r = 255;
            g = hue;
        } else {
            r = 510 - hue;
            g = 255;
        }
    } else if (hue < 1020) {
        r = 0;
        if (hue < 765) {
            g = 255;
            b = hue - 510;
        } else {
            g = 1020 - hue;
            b = 255;
        }
    } else if (hue < 1530) {
        g = 0;
        if (hue < 1275) {
            r = hue - 1020;
            b = 255;
        } else {
            r = 255;
            b = 1530 - hue;
        }
    } else {
        r = 255;
        g = b = 0;
    }

    color[0] = r;
    color[1] = g;
    color[2] = b;
}
